<?php
App::import('Controller', 'Comments.Comments');
class ReviewCommentsController extends CommentsController
{
	var $name = 'ReviewComments';
	protected $autoAdminActions = array('admin_bulkDelete','admin_bulkPublish','admin_bulkUnpublish');
	
	function beforeFilter()
	{
		parent::beforeFilter();
		$this->CommentAlias = 'Review comment';
	}
	function afteradd($lastInsertId,$itemId)
	{	
		$moderationOnComment = cr('ReviewConfig.use_moderation_on_comment');
		$message = 'Your comment has been published.';
		if($moderationOnComment == true)
		{
			$message = 'Your comment has been saved for moderation.';
		}else
		{
			$this->_sendNotificationMail($lastInsertId);
		}		
		$this->successMsg(__($message));
		if(strpos($this->referer(),'reviews/view'))
		{
			$this->Session->del('Message.ajax');
			Configure::write('debug',0);
			$this->layout = 'ajax';	
			echo __($message);exit;
		}
		$ajaxParam = '';
		if(isset($this->params['url']['ajax']) && $this->params['url']['ajax'] == 1)
		{
			$ajaxParam = '?ajax=1';
		}		
		$this->redirect(array('controller'=>'reviews','action'=>'view',$itemId.$ajaxParam));
	}
	
	function _sendNotificationMail($params)
	{
		$this->ReviewComment->recursive = 0;
		if(is_numeric($params))	
		{
			$reveiwCommentData = $this->ReviewComment->findById($params);	
		}
		$reviewUrl = cr('cmsConfig.Backend.siteUrl').'/reviews/view/'.$reveiwCommentData['Review']['id'];
		$this->set('username',$reveiwCommentData['Review']['poster']['display_name']);
		$this->set('commentator',$reveiwCommentData['ReviewComment']['poster']['display_name']);
		$this->set('reviewUrl',$reviewUrl);
		$sendMailOnAddedReviewGetComment = $this->ReviewComment->User->field('onAddedReviewGetComment',array('User.id'=>$reveiwCommentData['Review']['poster']['id']));
		if($sendMailOnAddedReviewGetComment && ($reveiwCommentData['ReviewComment']['user_id'] != $reveiwCommentData['Review']['user_id']))
		{
			App::import('Vendor', 'EmailOperation');
			EmailOperation::sendMail('MailOnAddedReviewGetComment',array($this,$reveiwCommentData));
		}
		$userList = $this->ReviewComment->User->find('all',array('conditions'=>array('User.onCommentedReviewGetComment'),'recursive'=>-1));
		if(!empty($userList))
		{
			$userIdList = Set::extract('{n}.User.id',$userList);
			$condition = array('ReviewComment.user_id'=>$userIdList,'NOT'=>array('ReviewComment.user_id'=>$reveiwCommentData['ReviewComment']['user_id']),'ReviewComment.review_id'=>$reveiwCommentData['ReviewComment']['review_id']);
			$userIdsToSendMail = $this->ReviewComment->find('list',array('fields'=>array('ReviewComment.user_id','ReviewComment.user_id'),'conditions'=>$condition));
			$userList = Set::combine($userList,'{n}.User.id','{n}.User');
			
			if(!empty($userIdsToSendMail))
			{
				App::import('Vendor', 'EmailOperation');
				EmailOperation::sendMail('MailOnCommentedReviewGetComment',array($this,$userList,$userIdsToSendMail,$reveiwCommentData));
			}
		}	
		
	}
	
	function admin_index()
	{
		if(isset($this->params['named']['search']))
		{
			$this->admin_search();
		}else
		{
			$this->helpers[] = 'Cms.Index';
			$this->pageTitle = __("Review Comments");
			$this->paginate['order'] = array('ReviewComment.created DESC');
			$this->paginate['recursive'] = 0;
			$this->paginate['limit'] = 10;
			$reviewComments = $this->paginate();
			$this->set(compact('reviewComments'));
		}
	}
	
	function admin_view($id = null)
	{
		$this->ReviewComment->recursive = 0;
		$commentData = $this->ReviewComment->findById($id);
		if(empty($commentData))
		{
			$this->errorMsg(__("Invalid URL"));
			$this->redirect($this->referer());
		}
		$listingName = $this->ReviewComment->Review->Listing->field('title',array('Listing.id'=>$commentData['Review']['listing_id']));
		$this->set(compact('commentData','listingName'));
		
	}
	
	function admin_edit($id)
	{
		$this->ReviewComment->recursive = -1;
		$commentData = $this->ReviewComment->findById($id);
		if(empty($commentData))
		{
			$this->errorMsg(__("Invalid URL"));
			$this->redirect($this->referer());
		}
		if($this->data)
		{
			$this->data['ReviewComment']['user_id'] = $commentData['ReviewComment']['user_id'];
			$this->data['ReviewComment']['review_id'] = $commentData['ReviewComment']['review_id'];
			
			if($this->ReviewComment->save($this->data))
			{
				$this->successMsg(__("Review Comment has been updated."));
				$this->redirect(array('controller'=>'review_comments','action'=>'admin_index'));
			}else
			{
				$this->errorMsg(__("Review Comment could not be updated."));
			}
		}
		$this->data = $commentData;
		$this->set(compact('commentData'));
	}
	
	function userComments()
	{
		$allowReviewComment = cr('ReviewConfig.allow_comment');
		if($allowReviewComment == false)
		{
			$this->__invalidUrl("Invalid URL",$this->referer());
		}
		$authedUser = $this->Session->read('Auth.User');
		if(!isset($this->params['named']['user']))
		{
			if(isset($this->params['named']['my']))
			{
				$this->params['named']['user'] = $this->Session->read('Auth.User.slug');
			}else
			{
				$this->__invalidUrl("Invalid URL",$this->referer());
			}
		}
		$userSlug = $this->params['named']['user'];
		$user = $this->ReviewComment->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		if(empty($user))
		{
			$this->__invalidUrl("Invalid URL",$this->referer());
		}
		$title = sprintf(__('%s\'s Comments'),$user['User']['display_name']);
		if($authedUser['id'] == $user['User']['id'])
		{
			$this->params['named']['my'] = 1;
			unset($this->params['named']['user']);
			$title = __("My Comments");
		}
		$this->pageTitle = $title;
		$this->paginate['conditions'] = array('ReviewComment.user_id'=>$user['User']['id'],'ReviewComment.status'=>ReviewComment::PUBLISH);
		$this->paginate['order'] = array('ReviewComment.created DESC');
		$this->paginate['limit'] = 10; 
		$comments = $this->paginate();
		
		$listingIds = Set::extract('{n}.Review.listing_id',$comments);
		$listingIds = array_unique($listingIds);
		$listingInfo = $this->ReviewComment->Review->Listing->find('all',array('conditions'=>array('Listing.id'=>$listingIds),'recursive'=>-1));
		$listingInfo = Set::combine($listingInfo,'{n}.Listing.id','{n}.Listing');
			
		$this->set(compact('comments','listingInfo','user'));	
	}
	
	function __invalidUrl($msg = null, $url = null)
	{
		if(empty($msg))
		{
			$msg = __("Invalid URL");
		}
		if(empty($url))
		{
			$url = "/";
		}
		$this->errorMsg($msg);
		$this->redirect($url);
	}
	
	function admin_search()
	{
		$this->helpers[] = 'Cms.Index';
		$default = array(
			'title'=>'',
			'submitter_name'=>'',
			'list_category_id'=>'',
			'status'=>'',
		);
		if($this->data)
		{
			$queryString = '';
			foreach($this->data['ReviewComment'] as $field=>$value)
			{
				$queryString .= $field.':'.$value.'/';
			}		
			//$url = am(array('action'=>'search','prefix'=>'admin'),$this->data['ReviewComment']);
			$this->redirect('/admin/review_comments/search/'.$queryString);
		}					
		$params = am($default,$this->params['named']);		
		if(!empty($params['title']))
		{
			$this->paginate['conditions']['AND'][] = array('ReviewComment.title LIKE'=>'%'.$params['title'].'%');	
		}
			
		if(!empty($params['submitter_name']))
		{
			if($params['status'] != 'guest_comments')
			{
				$user_ids = $this->ReviewComment->User->find('list',array('fields'=>'User.id','conditions'=>array('username LIKE'=>'%'.$params['submitter_name'].'%')));
				$this->paginate['conditions']['AND'][] = array('ReviewComment.user_id'=>$user_ids);
			}

			$guest_ids = $this->ReviewComment->Guest->find('list',array('fields'=>'Guest.id','conditions'=>array('Guest.name LIKE'=>'%'.$params['submitter_name'].'%')));
			$this->paginate['conditions']['AND'][] = array('ReviewComment.guest_id'=>$guest_ids);		
		}
			
		if(!empty($params['list_category_id']))
		{
			$categoryIds = $params['list_category_id'];
			$this->paginate['conditions']['AND'][] = array('Review.list_category_id'=>$categoryIds);	
		}
			
		if($params['status'] !=='')
		{
			if($params['status'] == 'guest_comments')
			{
				$this->paginate['conditions']['AND'][] = array('ReviewComment.user_id'=>null);
			}
			else
			{
				$this->paginate['conditions']['AND'][] = array('ReviewComment.status'=>$params['status']);
			}
		}		
			
		
		$this->paginate['order'] = array('ReviewComment.created DESC');
		$this->paginate['limit'] = 10;
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('searchParams',$params);
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		$reviewComments = $this->paginate();
		$this->set(compact('reviewComments'));
		$this->render('admin_index');
	}	
	function add($item_id=null)
	{
		if(cr('ReviewConfig.captha_on_review_guest_comment') == true && isset($this->data['ReviewComment']['captcha']))
		{			
			Configure::write('debug',0);
			$this->layout = 'ajax';		
			$validCaptcha = $this->verifyCaptcha($this->data['ReviewComment']['captcha']);
			if($validCaptcha == false)
			{
				exit;
			}
		}		
		parent::add($item_id);		
	}	
}
?>